import logging

from coin.strategy.accounting.pnl_balance_printer.pnl_balance_printer import (
    FuturesPnlBalancePrinter)
from coin.strategy.accounting.pnl_balance_printer.util import calculate_unrealized_pnl
from coin.support.pta.logic.pta_stats_calculator import (get_futures_multiplier, is_inverse_product)


class OkexFuturesPnlBalancePrinter(FuturesPnlBalancePrinter):
  def __init__(self, products, bookmap, reserve_map, logger=None):
    super().__init__(products,
                     bookmap,
                     reserve_map,
                     logger=(logger or logging.getLogger('OkexFuturesPnlBalancePrinter')))

  # We use margin balance because avg_entry_price given by Okex can be wrong, leading to
  # wrong unrealized pnl. Therefore, we don't calculate unrealized pnl by ourselves,
  # instead we use margin_balance directly, which includes unrealized pnl given by Okex.
  def get_balance(self, currency):
    return self._og.og_info.get_margin_balance(currency)

  def _get_pos(self, product):
    book = self._bookmap.get_book(product)
    if book is None or not book.has_ask() or not book.has_bid():
      return None, None

    pos = self._og.get_okex_futures_position(product)
    pos_multiplier = get_futures_multiplier('Futures', 'Okex', product.symbol)
    inverse = is_inverse_product(product)

    long_pos = pos.long * pos_multiplier
    long_unrealized_pnl = 0
    """
    long_unrealized_pnl = calculate_unrealized_pnl(product,
                                                   long_pos,
                                                   pos.long_avg_price,
                                                   book.ask0().price,
                                                   book.bid0().price,
                                                   inverse=inverse)
    """

    short_pos = -pos.short * pos_multiplier
    short_unrealized_pnl = 0
    """
    short_unrealized_pnl = calculate_unrealized_pnl(product,
                                                    short_pos,
                                                    pos.short_avg_price,
                                                    book.ask0().price,
                                                    book.bid0().price,
                                                    inverse=inverse)
    """

    net_pos = long_pos + short_pos
    net_unrealized_pnl = long_unrealized_pnl + short_unrealized_pnl
    return net_pos, net_unrealized_pnl
